<template>
  <view class="bg-[#f5f5f5] min-h-screen flex flex-col pb-10">
    <PageHeader title="推广中心" :showBack="true" />
    <!-- 推广二维码区域 -->
    <view class="bg-white rounded-[24rpx] shadow-md p-[32rpx] mx-[24rpx] mt-[24rpx]" v-show="hasCode">
      <view class="flex justify-between items-center mb-[32rpx]">
        <text class="text-[32rpx] font-bold text-[#333]">我的推广二维码（{{userRecommendCode}}）</text>
      </view>
      
      <view class="flex flex-col items-center">
        <view class="relative">
                     <!-- 二维码主体 -->
           <view class="w-[400rpx] h-[400rpx] bg-white border-[8rpx] border-[#165DFF] rounded-[24rpx] flex items-center justify-center relative">
             <view class="w-[320rpx] h-[320rpx] bg-[#f5f5f5] rounded-[16rpx] flex items-center justify-center relative">
               <image 
                 v-if="qrCodeUrl"
                 :src="qrCodeUrl" 
                 class="w-full h-full rounded-[12rpx]"
                 mode="aspectFit"
                 @error="handleQRCodeError"
                 @load="handleQRCodeLoad"
               />
               <view v-else class="flex items-center justify-center">
                 <view v-if="qrCodeLoading" class="flex flex-col items-center">
                   <view class="w-[60rpx] h-[60rpx] border-[4rpx] border-[#165DFF] border-t-transparent rounded-full animate-spin mb-[16rpx]"></view>
                   <text class="text-[24rpx] text-[#666]">生成二维码中...</text>
                 </view>
                 <view v-else>
                   <IconFont name="qrcode" size="120" color="#165DFF" />
                 </view>
               </view>
             </view>
           </view>
          
          <!-- 装饰性边框 -->
          <view class="absolute -top-[8rpx] -left-[8rpx] -right-[8rpx] -bottom-[8rpx] border-[2rpx] border-[#E3F2FD] rounded-[32rpx] opacity-50"></view>
        </view>
        
         <view class="mt-[32rpx] text-center">
           <text class="text-[28rpx] text-[#666]">扫码注册成为您的专属会员</text>
           <view class="mt-[16rpx]">
             <text class="text-[24rpx] text-[#999]">分享二维码，获得推广奖励</text>
           </view>
         </view>
      </view>
    </view>

    <TabList />

    <!-- 佣金规则说明 -->
    <view class="bg-white rounded-[24rpx] shadow-md p-[24rpx] mt-[24rpx] mx-[24rpx]">
      <view class="text-[30rpx] font-bold mb-[16rpx]">佣金规则说明</view>
      <view class="flex items-start mb-[16rpx]">
        <IconFont name="user-friends" class="text-[40rpx] text-[#165DFF] mr-[16rpx]" />
        <view class="flex-1">
          <text class="text-[26rpx] font-bold">个人端会员推广</text>
          <text class="block text-[24rpx] text-[#666] mt-[4rpx]">每成功推广1名个人付费用户，可获得<text class="text-[#FF4D4F] font-bold">10元</text>固定奖励。奖励在用户完成付费后实时发放。</text>
        </view>
      </view>
      <view class="flex items-start mb-[16rpx]">
        <IconFont name="building" class="text-[40rpx] text-[#fa8c16] mr-[16rpx]" />
        <view class="flex-1">
          <text class="text-[26rpx] font-bold">企业端会员推广</text>
          <text class="block text-[24rpx] text-[#666] mt-[4rpx]">每成功推广1家企业付费用户，可获得该企业<text class="text-[#FF4D4F] font-bold">实际付费金额×30%</text>的佣金奖励。押金部分不计提佣金。</text>
        </view>
      </view>
      <view class="flex items-start">
        <IconFont name="graduation-cap" class="text-[40rpx] text-[#52c41a] mr-[16rpx]" />
        <view class="flex-1">
          <text class="text-[26rpx] font-bold">技能传承商推广</text>
          <text class="block text-[24rpx] text-[#666] mt-[4rpx]">成功推广技能传承商目前仅记录数量，具体佣金政策将在后续公布。请关注平台通知。</text>
        </view>
      </view>
    </view>

    <!-- 日期选择器 -->
    <nut-popup v-model:visible="showDatePicker" position="bottom" round>
      <nut-date-picker
        v-model="dateValue"
        title="选择日期"
        type="date"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="handleDateConfirm"
        @cancel="showDatePicker = false"
      />
    </nut-popup>

  </view>
</template>

<script>
import {ref, reactive, onMounted, watch} from 'vue';
import { IconFont } from '@nutui/icons-vue-taro';
import Taro from '@tarojs/taro';
import PageHeader from '@/components/PageHeader.vue'
import {post} from "@/utils/request";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";
import QRCode from 'qrcode';
import TabList from '@/components/tab-list.vue';
const userStore = useUserStore();

console.log("userStore info==--==-==", userStore.userInfo);

export default {

  components: {
    IconFont
  },
     setup() {
     // 获取用户store
     const { userInfo } = storeToRefs(userStore);
     const hasCode = ref(false);
    //  const hasCode = ref(false); 
    hasCode.value = userInfo.value.promoter == 1;
    console.log("hasCode", hasCode.value);
     
     // 数据筛选选项
     const filterItems = ref([
       { icon: 'calendar-day', label: '今日' },
       { icon: 'calendar-week', label: '本周' },
       { icon: 'calendar-alt', label: '本月' },
       { icon: 'history', label: '历史' }
     ]);
     const activeFilter = ref(0);
    
         // 推广明细数据
     const promotionList = ref([
       { }
     ]);
     
     // 二维码相关
     const qrCodeUrl = ref('')
     const userRecommendCode = ref('')
     const qrCodeLoading = ref(false)
    
    // 日期选择相关
    const showDatePicker = ref(false)
    const dateValue = ref(new Date())
    const minDate = ref(new Date('2023-01-01'))
    const maxDate = ref(new Date('2030-12-31'))
    const selectedDate = ref(formatDate(new Date()))
    function formatDate(date) {
      if (!date) return '';
      const y = date.getFullYear();
      const m = (date.getMonth() + 1).toString().padStart(2, '0');
      const d = date.getDate().toString().padStart(2, '0');
      return `${y}-${m}-${d}`;
    }
    const handleDateConfirm = (val) => {
      showDatePicker.value = false;
      dateValue.value = val;
      selectedDate.value = formatDate(val);
    }
    
    // 底部导航
    const footerItems = ref([
      { icon: 'home', label: '首页' },
      { icon: 'chart-line', label: '统计' },
      { icon: 'share-alt', label: '推广' },
      { icon: 'wallet', label: '收益' },
      { icon: 'user', label: '我的' }
    ]);
    const activeTab = ref(2);
    
    // 事件处理
    const handleBack = () => {
      Taro.navigateBack();
    };
    
    const changeFilter = (index) => {
      activeFilter.value = index;
      Taro.showToast({
        title: `切换到${filterItems.value[index].label}数据`,
        icon: 'none'
      });
    };
    
    const handleCardClick = (type) => {
      let typeName = '';
      if (type === 'personal') typeName = '个人端';
      else if (type === 'business') typeName = '企业端';
      else typeName = '技能传承商';
      
      Taro.showToast({
        title: `查看${typeName}详细数据`,
        icon: 'none'
      });
    };
    
    const handleRowClick = (item) => {
      Taro.showToast({
        title: `查看${item.target}详情`,
        icon: 'none'
      });
    };

    // 保存二维码
    const handleSaveQRCode = () => {
      Taro.showToast({
        title: '二维码保存功能开发中',
        icon: 'none'
      });
    };

         // 分享二维码
     const handleShareQRCode = () => {
       Taro.showToast({
         title: '分享功能开发中',
         icon: 'none'
       });
     };

     // 生成二维码URL
     const generateQRCodeUrl = async () => {
       if (!userRecommendCode.value) {
         console.warn('用户推荐码为空，无法生成二维码')
         return
       }
       
       try {
         qrCodeLoading.value = true
         
         // 获取当前域名
         const currentDomain = window.location.origin || 'https://www.nl9555.com'
         const qrData = currentDomain + '?recommend=' + userRecommendCode.value
         
         // 使用qrcode库生成二维码
         const dataUrl = await QRCode.toDataURL(qrData, {
           width: 300,
           height: 300,
           margin: 2,
           color: {
             dark: '#000000',
             light: '#FFFFFF'
           }
         })
         
         qrCodeUrl.value = dataUrl
        //  console.log('生成的二维码URL:', qrCodeUrl.value)
       } catch (error) {
         console.error('生成二维码失败:', error)
         Taro.showToast({
           title: '生成二维码失败',
           icon: 'none'
         })
       } finally {
         qrCodeLoading.value = false
       }
     }

           // 获取用户推荐码
      const getUserRecommendCode = async () => {
        try {
          console.log('当前用户信息:', userInfo.value)
          
          // 从store中获取用户推荐码
          if (userInfo.value && userInfo.value.recommend_code) {
            userRecommendCode.value = userInfo.value.recommend_code
            console.log('从store获取用户推荐码:', userRecommendCode.value)
            await generateQRCodeUrl()
          } else if (userInfo.value && userInfo.value.recommendCode) {
            // 兼容不同的字段名
            userRecommendCode.value = userInfo.value.recommendCode
            console.log('从store获取用户推荐码(兼容字段):', userRecommendCode.value)
            await generateQRCodeUrl()
          } else {
            console.warn('用户信息中未找到推荐码，用户信息:', userInfo.value)
            Taro.showToast({
              title: '未找到推荐码信息',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('获取推荐码异常:', error)
          Taro.showToast({
            title: '获取推荐码异常',
            icon: 'none'
          })
        }
      }

     // 二维码加载错误处理
     const handleQRCodeError = (e) => {
       console.error('二维码加载失败:', e)
       qrCodeUrl.value = ''
       Taro.showToast({
         title: '二维码加载失败',
         icon: 'none'
       })
     }

     // 二维码加载成功处理
     const handleQRCodeLoad = (e) => {
       console.log('二维码加载成功:', e)
     }


    const myRecommendation = async () =>{
      const data = await post('/my/recommend')
      promotionList.value = data.data.map(item => item.columns);
      console.log("promotionList",promotionList)
    }



    const changeTab = (index) => {
      activeTab.value = index;
      if (index !== 2) {
        Taro.showToast({
          title: `切换到${footerItems.value[index].label}页面`,
          icon: 'none'
        });
      }
    };

                             // 组件挂载后调用，获取初始数据
       onMounted(async () => {
         myRecommendation();
         
         await getUserRecommendCode(); // 从store获取用户推荐码并生成二维码
       });

       // 监听用户信息变化，自动更新二维码
       watch(userInfo, async (newUserInfo) => {
         if (newUserInfo && newUserInfo.recommend_code && newUserInfo.recommend_code !== userRecommendCode.value) {
           console.log('用户信息更新，重新生成二维码')
           await getUserRecommendCode()
         }
       }, { deep: true })

         return {
       filterItems,
       activeFilter,
       promotionList,
       qrCodeUrl,
       qrCodeLoading,
       userRecommendCode,
       showDatePicker,
       dateValue,
       minDate,
       maxDate,
       selectedDate,
       handleDateConfirm,
       footerItems,
       activeTab,
       handleBack,
       changeFilter,
       handleCardClick,
       handleRowClick,
       handleSaveQRCode,
       handleShareQRCode,
       handleQRCodeError,
       handleQRCodeLoad,
       changeTab,
       hasCode
     };
  }
};
</script>

<style lang="scss" scoped>
</style>